package cn.gailvlun.gll.presentation.emotion.edit

import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.app.DialogFragment
import android.content.Intent
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.view.View
import android.widget.CheckBox
import cn.gailvlun.gll.R
import cn.gailvlun.gll.databinding.DialogEmotionPostBinding
import cn.gailvlun.gll.net.GsonUtil
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.net.emotion.*
import cn.gailvlun.gll.presentation.base.BaseActivity
import cn.gailvlun.gll.presentation.emotion.drawer.EmotionPersonalActivity
import cn.gailvlun.gll.util.*
import cn.gailvlun.gll.widget.photopicker.PhotoItem
import com.blankj.utilcode.util.KeyboardUtils
import org.joda.time.DateTime


const val PREF_IS_REMEMBER_NOTE = "pref_is_remember_note"
const val ARG_RECORD_REQ = "arg_record_req"
const val TAG_DIALOG_EMOTION_POST = "tag_dialog_emotion_post"

class EmotionPostDialog : DialogFragment() {


    var mReq: EmotionRecordReq = EmotionRecordReq()

    val draftDialog: DraftDialog = DraftDialog.getInstance()
    lateinit var activity: BaseActivity

    companion object {
        fun newInstance(): EmotionPostDialog {
            val dialog = EmotionPostDialog()
            return dialog
        }
    }

    
    @Deprecated("")
    fun showIfNeed(activity: BaseActivity, emotionTagReq: EmotionTagReq?, text: String?, photoItemList: List<PhotoItem>?) {

        

        if (emotionTagReq != null) {

            if (IsEmpty.string(emotionTagReq.title)) {
                ToastUtil.showShort("不存在 title")
                return
            }





        } else {
            ToastUtil.showShort("EmotionTagReq 不存在")
            return
        }

        this.activity = activity
        mReq = EmotionRecordReq()
        if (!emotionTagReq.isUserCreated) {
            mReq.emotionTagId = emotionTagReq.id

        }
        if (!IsEmpty.string(text)) {
            mReq.text = text
        }
        if (!IsEmpty.list(photoItemList)) {
            mReq.pics = PhotoItem.transform2oss(photoItemList)
        }

        val isRememberNote = SPUtil.getBoolean(SPUtil.USER, PREF_IS_REMEMBER_NOTE)
        if (IsEmpty.string(text) && IsEmpty.list(photoItemList) && !isRememberNote) {
            show(activity.fragmentManager, TAG_DIALOG_EMOTION_POST)
        } else {
            if (emotionTagReq.isUserCreated) {
                uploadEmotionTag(emotionTagReq)
            } else {
                record(mReq)
            }
        }

    }

    
    fun showIfNeed2(activity: BaseActivity, emotionTagReq: EmotionTagReq?, text: String?, photoItemList: List<PhotoItem>?) {

        this.activity = activity
        mReq = EmotionRecordReq()

        if (!IsEmpty.string(text)) {
            mReq.text = text
        }
        if (!IsEmpty.list(photoItemList)) {
            mReq.pics = PhotoItem.transform2oss(photoItemList)
        }

        if (!IsEmpty.string(text) || !IsEmpty.list(photoItemList)) {
            if (emotionTagReq != null && emotionTagReq.isUserCreated) {
                uploadEmotionTag(emotionTagReq)
            } else {
                mReq.emotionTagId = emotionTagReq?.id
                record(mReq)
            }
        }

    }

    
    fun showIfNeed3(activity: BaseActivity, filterEnum: FilterEnum?, emotionTagReq: EmotionTagReq?, text: String?, photoItemList: List<PhotoItem>?) {

        this.activity = activity

        mReq = EmotionRecordReq()
        if (filterEnum == null) {
            ToastUtil.showShort("请选择情绪分类")
            return
        } else {
            mReq.emo_big_type = filterEnum
        }

        if (!IsEmpty.string(text)) {
            mReq.text = text
        } else {


        }

        if (!IsEmpty.list(photoItemList)) {
            mReq.pics = PhotoItem.transform2oss(photoItemList)
        }

        if (!IsEmpty.string(text) || !IsEmpty.list(photoItemList)) {
            if (emotionTagReq != null && emotionTagReq.isUserCreated) {
                uploadEmotionTag(emotionTagReq)
            } else {
                mReq.emotionTagId = emotionTagReq?.id
                record(mReq)
            }
        }

    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val binding = DataBindingUtil.inflate<DialogEmotionPostBinding>(activity.layoutInflater, R.layout.dialog_emotion_post, null, false)
        binding.request = mReq
        binding.presenter = Presenter()
        return AlertDialog.Builder(activity)
                .setView(binding.root)
                .create()
    }

    var pd: Dialog? = null
    private fun uploadEmotionTag(req: EmotionTagReq) {
        pd = DialogUtil.showIndeterminate(activity)
        HttpMethods.getEmotionService()
                .createEmotionTag(req)
                .compose(RxUtil.applyScheduler())
                .subscribe(object : HttpSubscriber<EmotionTag>() {
                    override fun onSuccess(response: EmotionTag?) {
                        pd?.dismiss()
                        if (response != null) {
                            mReq.emotionTagId = response.id
                            record(mReq)
                        }
                    }

                    override fun onFailure(errMsg: String?, response: EmotionTag?, code: Int) {
                        pd?.dismiss()
                        DialogUtil.showError(activity, errMsg)
                    }
                })


    }


    fun record(req: EmotionRecordReq) {
        req.early_today = DateTime.now().withTimeAtStartOfDay().millis / 1000
        HttpMethods.getEmotionService()
                .emotionRecord(req)
                .compose(RxUtil.applyScheduler())
                .subscribe(object : HttpSubscriber<Emotion>() {
                    override fun onSuccess(response: Emotion) {
                        pd?.dismiss()
                        draftDialog.clearDraft()
                        if (KeyboardUtils.isSoftInputVisible(activity)) {
                            KeyboardUtils.hideSoftInput(activity)
                        }
                        if (IsEmpty.string(response.text) && IsEmpty.list(response.pics)) {
                            EmotionPersonalActivity.openActivity(activity)
                        } else {
                            
                            val intent = Intent()
                            intent.putExtra("type", response.emotion)
                            intent.putExtra("extra_emotion_obj", GsonUtil.getGson().toJson(response))

                            activity.setResult(Activity.RESULT_OK, intent)
                        }
                        activity.finish()
                    }

                    override fun onFailure(errMsg: String, response: Emotion?, code: Int) {
                        pd?.dismiss()
                        DialogUtil.showError(activity, errMsg)
                        ToastUtil.showShort("发布失败")
                    }
                })
    }


    inner class Presenter {

        fun onRememberNote(view: View) {

            val checkBox = view as CheckBox
            if (checkBox.isChecked) {
                SPUtil.put(SPUtil.USER, PREF_IS_REMEMBER_NOTE, true)
            } else {
                SPUtil.put(SPUtil.USER, PREF_IS_REMEMBER_NOTE, false)

            }
        }

        fun onPost(view: View, req: EmotionRecordReq) {
            mReq.text = null
            record(mReq)
            dialog.dismiss()
        }

        fun onCancel(view: View) {
            dialog.dismiss()
            SPUtil.put(SPUtil.USER, PREF_IS_REMEMBER_NOTE, false)

        }

    }


}